import axios from "axios";
import type {
	AxiosError,
	AxiosInstance,
	AxiosPromise,
	AxiosRequestConfig,
	AxiosResponse,
	InternalAxiosRequestConfig
} from "axios";

type Instance = AxiosInstance & {
	[K: string]: any;
};

export type RequestReturnType = {
	code?: string;
	data: any;
};

const instance: Instance = axios.create({
	timeout: 12000,
	withCredentials: true,
	baseURL: "/bma-reform",
	headers: {
		"Content-Type": "application/json",
		"X-Requested-With": "XMLHttpRequest"
	}
});

/**
 * @description 统一处理请求并返回结果
 *
 * @param {String} url
 * @param {Object} params
 * @param {String} type
 *
 * @return {Promise}
 * */
const returnRequest = (url: string, params = {}, type: string) => {
	return new Promise((resolve, reject) => {
		instance[type](url, params)
			.then((result: AxiosResponse<RequestReturnType, any>) => {
				if (result["data"]) {
					resolve(result["data"]);
				} else {
					reject(result["data"]);
				}
			})
			.catch((error: AxiosError) => {
				reject(error);
			});
	});
};

/**
 * @description 请求前拦截
 * */
instance.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		return config;
	},

	(error: AxiosRequestConfig<any>) => {
		return Promise.reject(error);
	}
);

/**
 * @description 响应前拦截
 * */
instance.interceptors.response.use(
	(request: AxiosResponse) => {
		request.data.key = request.config.params;
		return request;
	},

	(error: AxiosRequestConfig) => {
		return Promise.reject(error);
	}
);

/**
 * @description GET 请求并返回请求
 * */
export const GET = (url: string, params = {}): AxiosPromise =>
	<AxiosPromise>returnRequest(url, { params }, "get");

/**
 * @description POST 请求并返回请求
 * */
export const POST = (url: string, params = {}): AxiosPromise =>
	<AxiosPromise>returnRequest(url, params, "post");
